package david.java.tools;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: groupset 去重
 * @Author: ZhaoDawei
 * @Date: Create in 8:43 下午 2022/8/19
 */
public class GroupSetHelper extends BaseUtil {
    public static void main(String[] args) throws IOException {
        String input = "src/tmp/src_groupingset";
        String output = "target-tmp/tmp_groupingset_deduplicate";

        mkdirIfNotExists(output);

        removeDuplicate(input, output, true);

    }

    public static void removeDuplicate(String input, String output, boolean printBlank) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(input));
        BufferedWriter bw = new BufferedWriter(new FileWriter(output));
        Set<Integer> set = new HashSet<>();
        List<String> result = new ArrayList<>();

        String line;
        while ((line = br.readLine()) != null) {
            if (printBlank && StringUtils.isBlank(line)) {
                result.add(line);
            }
            if (StringUtils.isNotBlank(line)) {
                if (line.startsWith("--")) {
                    result.add(line);
                    continue;
                }
                int hashcode = hashcode(line);
                if (!set.contains(hashcode)) {
                    result.add(line);
                    set.add(hashcode);
                } else {
                    result.add("-- " + line + "\t\t\t-- TODO DUPLICATE");
                }
            }
        }

        for (int i = 0; i < result.size(); i++) {
            bw.write(result.get(i));
            bw.newLine();
        }

        bw.flush();
        br.close();
        bw.close();
    }

    public static int hashcode(String line) {

        line.trim();
        if (line.startsWith("(")) {
            line = line.substring(1);
        }
        if (line.endsWith(",")) {
            line = line.substring(0, line.length() - 1);
            line.trim();
        }
        if (line.endsWith(")")) {
            line = line.substring(0, line.length() - 1);
        }

        String[] split = line.split(",");
        List<String> collect = Arrays.stream(split).map(String::trim).sorted().collect(Collectors.toList());
        String join = String.join(",", collect);
        return join.hashCode();
    }
}
